<template>
	<view>
		<uni-drawer
			ref="drawerRef"
			:mode="mode"
			:mask="mask"
			:maskClick="maskClick"
			:width="width"
		>
		<view style="background: #F8F8F8">
			<slot name="head">
				<view v-if="needSearch">
					<SearchComp @onChange="onChange"/>
				</view>
			</slot>
			<slot name="body">
				<view>
					<scroll-view :scroll-top="scrollTop"
								 scroll-y="true"
								 :style="scrollY"
								 @scrolltoupper="upper"
								 @scrolltolower="lower"
								 @scroll="scroll">
					<uni-list v-if="newList.length !== 0" :border="border">
						<view>
							<uni-list-item v-for="(item,index) in newList"
										   :key="item.key"
										   :title="item.title || ''"
										   :note="item.note || ''"
										   :ellipsis="item.title && item.note ? 1 : 2"
										   :rightText="item.rightText || ''"
										   :showBadge="item.showBadge === true ? true : false"
										   :badgeText="item.badgeText || ''"
										   :badgeType="item.badgeType || ''"
										   :disabled="item.disabled === true ? true : false"
										   :showArrow="item.showArrow === true ? true : false"
										   :link="item.link ? item.link : false"
										   :to="item.to || ''"
										   :thumb="needThumb || needCheckbox ? iconImgPath :''"
							>
								<view v-if="needThumb || needCheckbox" slot="header" class="uni-list-item__header">
									<view v-if="needCheckbox">
										<radio @click="onChecked($event,item.id)" :checked="item.checked"/>
									</view>
									<view v-if="needThumb" class="uni-list-item__icon">
										<image :src="item.thumb ? item.thumb : iconImgPath" class="uni-list-item__icon-img"/>
									</view>
								</view>
							</uni-list-item>
						</view>
					</uni-list>
					<uni-load-more v-if="loading && newList.length == 0 || newList.length > 0 " :status="status"/>
					<emptyData v-if="!loading && newList.length == 0" :needRefresh="true" @refresh="refresh"/>
					</scroll-view>
				</view>
			</slot>
			<slot name="footer">
				<view v-if="needFooter" class="footer d-flex justify-between align-center pd10 bagW">
					<view class="wp50">
						<buttonComp :defaultColor="true" type="default" @onClick="onCanle">取消</buttonComp>
					</view>
					<view class="wp50 mgl10">
						<buttonComp type="primary" @onClick="onOk">确定</buttonComp>
					</view>
				</view>
			</slot>
		</view>

		</uni-drawer>
	</view>
</template>

<script>
	import {UniDrawer,uniList,uniListItem,uniLoadMore} from "@dcloudio/uni-ui"
	import SearchComp from "../search-comp/search-comp"
	import emptyData from "../empty-data/empty-data"
	import bottomLine from "../bottom-line/bottom-line"
	import buttonComp from "../button-comp/button-comp"
	import {listPage,getListPage, setList} from "../common/helper"
	import iconImgPath from '../common/static/images/avatar.png';
	import isFunction from "lodash/isFunction"
	import isEmpty from "lodash/isEmpty"
	import forEach from "lodash/forEach"
	import map from "lodash/map"
    export default {
		components:{
			UniDrawer,
			SearchComp,
			emptyData,
			bottomLine,
			buttonComp,
			uniList,
			uniListItem,
			uniLoadMore
		},
		props:{
			callback:{ //使用组件内接口请求回调值
				type:Boolean,
				default:false,
			},
			searchData:{ //fields = [], condition = ''
				type:Object,
				default:()=>{
					return {}
				},
			},
			finderCode:{
				type:String,
				default:'',
			},
			func:{
				type:Function,
				default:null
			},
			listApi:{ //请求aqi
				type:String,
				default:'',
			},
			needSearch:{
				type: Boolean,
				default: true
			},
			needFooter:{
				type: Boolean,
				default: true
			},
			headerH:{
				type: Number,
				default: 52
			},
			footerH:{
				type: Number,
				default: 68
			},
			compData:{ //主数据
				type:Array,
				default:()=>{
					return []
				}
			},
			paramsKeys:{ //根據key去显示title,content，thumb...
				type:Object,
				default:()=>{
					return {
						name:'title',
						code:'note',
						url:'thumb'
					}
				}
			},
			changeKey:{
				type: String,
				default: 'id', //id, code
			},
			checkedBox:{
				type: String,
				default: 'radio', //radio, checkbox
			},
			needThumb:{
				type: Boolean,
				default: false
			},
			needCheckbox:{
				type: Boolean,
				default: false
			},
			border:{
				type: Boolean,
				default: false
			},
			isMountedReq:{
				type: Boolean,
				default: false
			},
			/**
			 * 显示模式（左、右），只在初始化生效
			 */
			mode: {
				type: String,
				default: ''
			},
			/**
			 * 蒙层显示状态
			 */
			mask: {
				type: Boolean,
				default: true
			},
			/**
			 * 遮罩是否可点击关闭
			 */
			maskClick:{
				type: Boolean,
				default: false
			},
			/**
			 * 抽屉宽度
			 */
			width: {
				type: Number,
				default: 220
			},
			params:{
				default:null
			}
		},
        data(){
        	return {
				iconImgPath:iconImgPath,
				keyword:'',
				scrollTop:0,
				old:{
					scrollTop:0,
				},
				list:{
					...listPage,
				},
				dataList:[],
				loading:false,

			}
		},
		watch:{
			compData(data){
				this.dataList = data;
			},
			list(values){
				this.list = values;
			},
		},
		computed:{
			status(){
				let {pages, current} = this.list;
				let status = '';
				if(this.loading){
					status = 'loading'
				}else if(this.loading === false && pages > current){
					status = 'more'
				}
				return status;
			},
			scrollY(){
				let y = '500';

				//#ifdef H5
				y = document.body.offsetHeight;
				//#endif
				//#ifndef H5
				y = uni.getSystemInfoSync().screenWidth
				//#endif
				return `height:${y-this.footerH-this.headerH}px`;
			},
			ps(){
				let {current,size} = this.list;
				return {
					startIndex:(current-1) * size,
					maxResult:size,
					searchText:this.keyword,
					...this.searchData
				}
			},
			newList(){
				let compData = this.dataList;
				let {list} = this.list;
				let data = [], newData=[];
				if(!isEmpty(compData)) data =  compData;
				if(!isEmpty(list)) data =  list;

				forEach(data,item=>{
					let newItem = {...item};
					if(!isEmpty(this.paramsKeys)){
						map(this.paramsKeys,(value,key)=>{
							newItem[value] = newItem[key]
						})
					}
					newData.push(newItem)
				});

				return newData;
			}
		},
		created() {
			this.dataList = this.compData;
			if(this.isMountedReq){
				this.fetchReq();
			}
		},
		methods:{
			refresh(){
				this.clear();
				this.fetchReq();
			},
			clear(){
				this.keyword='';
				this.scrollTop=0;
				this.old={
					scrollTop:0
				};
				this.list={
					...listPage
				};
				this.dataList=[];
				this.loading=false;
			},
			onChecked(e,id){
				let data = this.newList,newData=[];
				forEach(data,item=>{
					let newItem = {...item};
					if(this.checkedBox==='radio'){
						if(newItem.id === id){
							newItem.checked = true
						}else{
							newItem.checked = false
						};
					}else{
						if(newItem.id === id){
							newItem.checked = !newItem.checked
						}
					}
					newData.push(newItem)
				});
				if(!isEmpty(this.dataList)){
					this.dataList = newData;
				}else{
					this.list.list = newData;
				}
			},
			upper(e) {//滚动到顶部
				console.log('upper',e)
			},
			lower(e) { //滚动到底部
				let { current, pages} = this.list;
				if(this.loading === false && pages > current){
					current++;
					this.list.current = current;
					this.loading = true;
					this.fetchList();
				}
			},
			scroll(e) {
				this.old.scrollTop = e.detail.scrollTop
			},
			goTop() {
				this.scrollTop = this.old.scrollTop;
				this.$nextTick(function() {
					this.scrollTop = 0
				});
			},
			open(){
				this.$refs.drawerRef.open();
				if(isEmpty(this.dataList) && isEmpty(this.list.list)) {
					this.fetchReq();
				}
			},
			onChange(values){
				let {keyword} = values;
				this.keyword = keyword;
				this.loading = true;
				this.list={
					...listPage
				};
				this.goTop();
				this.fetchReq(200);
			},
			fetchReq(time=0){
				setTimeout(this.fetchList,time);
			},
			async fetchList(){

				let params = {...this.ps};
				let res = null;
				if(this.listApi && this.config && isFunction(this.config.reqGet)){
					this.loading = true;
					res = await this.config.reqGet(this.listApi,params);
				}else if(isFunction(this.func)){
					this.loading = true;
					res = await this.func(params);
				}else if(this.finderCode && this.hepler && isFunction(this.hepler.fetchFinder)){
					this.loading = true;
					params.finderCode = this.finderCode;
					res = await this.hepler.fetchFinder(params);
				};
				if(res && isEmpty(this.compData)){

					this.loading = false;
					let newPayload = { ...this.list,list:[...this.list.list]};
					if(res && res.data && res.data.status == 200){
						newPayload = getListPage({
							...res.data.data,
							current:this.list.current
						});
						this.setList(newPayload)
					}
				}
			},
			setList(newPayload){
				this.list = setList({...this.list,list:[...this.list.list]},newPayload);
				if(this.callback){
					this.$emit('callback',{
						list:{...this.list}
					})
				}
				// console.log('this.list',this.list)
			},
			onCanle(){
				// this.clear();
				this.$refs.drawerRef.close();
			},
			onOk(){
				this.onCanle();
				this._change();
			},
			_change(){
				let data = this.newList;
				let selectRows= [],selectKeys=[];
				if(!isEmpty(data)){
					map(data,item=>{
						if(item.checked){
							selectKeys.push(item.id);
							selectRows.push({...item});
						}
					})
				}
				this.$emit('onChange',{
					selectKeys,
					selectRows,
					params:this.params
				})
			}
		}
    }
</script>

<style lang="scss" scoped>
	@import "../common/common.scss";
	.uni-list-item__header {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
		align-items: center;
	}
	.uni-list-item__icon {
		margin-right: 18upx;
		flex-direction: row;
		justify-content: center;
		align-items: center;
	}

	.uni-list-item__icon-img {
		/* #ifndef APP-NVUE */
		display: block;
		/* #endif */
		height: 110upx;
		width: 110upx;
		border-radius: 50%;
	}

	.footer{
		position: relative;
		left:0;
		bottom:0;
	}
</style>
